package com.quanquan.store.service;

import com.quanquan.store.entity.ShoppingKill;
import com.quanquan.store.entity.ShoppingKillAbnormal;
import com.quanquan.store.entity.ShoppingKillTradingRecord;
import com.quanquan.store.repository.ShoppingKillAbnormalRepository;
import com.quanquan.store.repository.ShoppingKillRepository;
import com.quanquan.store.repository.ShoppingKillTradingRecordRepository;
import com.quanquan.store.request.CouponRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import utils.CalendarUtil;
import utils.DateUtils;
import utils.UUIDGenerator;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能描述:
 *
 * @ClassName: ShoppingKillTradingRecordService
 * @Author: xiaoqianh丶
 * @Date: 2019-07-01 15:04
 * @Version: V1.0
 */
@Service
public class ShoppingKillTradingRecordService {

    private final CouponService couponService;
    public static final String INTEGRAL = "integral";
    public static final String MONEY = "money";

    public static final String USER_NUM = "userNum_";
    public static final String STRING = "_";
    private final ShoppingKillAbnormalRepository shoppingKillAbnormalRepository;
    public static final String INVENNTORY = "invenntory";

    private final StringRedisTemplate stringRedisTemplate;


    private final ShoppingKillRepository shoppingKillRepository;

    private final ShoppingKillTradingRecordRepository shoppingKillTradingRecordRepository;


    public ShoppingKillTradingRecordService(ShoppingKillTradingRecordRepository shoppingKillTradingRecordRepository, CouponService couponService, StringRedisTemplate stringRedisTemplate, ShoppingKillRepository shoppingKillRepository, ShoppingKillAbnormalRepository shoppingKillAbnormalRepository) {
        this.shoppingKillTradingRecordRepository = shoppingKillTradingRecordRepository;
        this.couponService = couponService;
        this.stringRedisTemplate = stringRedisTemplate;
        this.shoppingKillRepository = shoppingKillRepository;
        this.shoppingKillAbnormalRepository = shoppingKillAbnormalRepository;
    }
    public boolean createRecord(String userId, String shoppingKillId, String uuid) {

        //根据秒杀商品id查询秒杀信息和价格
        ShoppingKill shoppingKill = shoppingKillRepository.findByIdAndRemove(shoppingKillId, 0);
        if (shoppingKill != null) {
            //拿到商品id查询根据秒杀商品类型找到商品
            String goodsType = shoppingKill.getGoodsType();
            String shoppingKillGoods = shoppingKill.getShoppingKillGoods();
            ShoppingKillTradingRecord shoppingKillTradingRecord = new ShoppingKillTradingRecord();
            shoppingKillTradingRecord.setId(uuid);
            shoppingKillTradingRecord.setGoodId(shoppingKillGoods);
            shoppingKillTradingRecord.setGoodsType(goodsType);
            shoppingKillTradingRecord.setUseId(userId);
            shoppingKillTradingRecord.setOrderNumber(uuid);
            shoppingKillTradingRecord.setCreateTime(DateUtils.currentDate());
            String payType = shoppingKill.getPayType();
            /**
             * 支付类型  integral 积分  money 现金
             */
            if(INTEGRAL.equals(payType)){
               shoppingKillTradingRecord.setIntegral(shoppingKill.getIntegral());
               shoppingKillTradingRecord.setPrice(0.0);
                shoppingKillTradingRecord.setTradingStatus(ShoppingKillTradingRecord.TradingStatus.paid);
                //将抢到的优惠券生成领取记录

                CouponRequest couponRequest = new CouponRequest();
                couponRequest.setId(shoppingKill.getShoppingKillGoods());
                couponRequest.setUserId(userId);
                couponRequest.setSendRequestType(1);
                couponService.sendShoppingKillCoupon(couponRequest);

            }if(MONEY.equals(payType)){
                shoppingKillTradingRecord.setIntegral(0);
                shoppingKillTradingRecord.setPrice(shoppingKill.getPrice());
                shoppingKillTradingRecord.setTradingStatus(ShoppingKillTradingRecord.TradingStatus.unpaid);

            }
            shoppingKillTradingRecord.setPrice(shoppingKill.getPrice());
            shoppingKillTradingRecord.setShoppingKillId(shoppingKillId);

            shoppingKillTradingRecordRepository.saveAndFlush(shoppingKillTradingRecord);
            return true;
        }


        return false;




    }


    /**
     * 根据订单号查找订单
     *
     * @param orderNum
     * @return
     */
    public ShoppingKillTradingRecord findByOrderRecord(String orderNum) {
        return shoppingKillTradingRecordRepository.findById(orderNum).orElse(null);
    }


    //每个整点后更新活动状态
    public void timingProcessing() {
        List<ShoppingKillTradingRecord> allUnpaid = shoppingKillTradingRecordRepository.findAllUnpaid();
        if (allUnpaid.size()>0) {
            for (ShoppingKillTradingRecord shoppingKillTradingRecord : allUnpaid) {
                String createTime = shoppingKillTradingRecord.getCreateTime();
                //判断是有在3分钟以内
                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime createDate = LocalDateTime.parse(createTime, df);
                LocalDateTime now = LocalDateTime.now();
                Duration between = Duration.between(createDate, now);
                long differenceTime = between.toMillis();
                if (differenceTime >= 300000L) {
                    shoppingKillTradingRecord.setTradingStatus(ShoppingKillTradingRecord.TradingStatus.overdue);
                    shoppingKillTradingRecordRepository.saveAndFlush(shoppingKillTradingRecord);
                    incr(shoppingKillTradingRecord.getShoppingKillId());
                }
            }
        }
    }


    //访问自增计数
    public  Long incr(String key) {
        Long increment = stringRedisTemplate.opsForValue().increment(INVENNTORY + key, 1);

        return increment;
    }

    public boolean updateRecord(String outTradeNo, String transactionId,ShoppingKillTradingRecord order) {
        if(order == null){
            ShoppingKillAbnormal shoppingKillAbnormal = new ShoppingKillAbnormal();
            shoppingKillAbnormal.setId(UUIDGenerator.getUUID());
            shoppingKillAbnormal.setOutTradeNo(outTradeNo);
            shoppingKillAbnormal.setCreateTime(DateUtils.currentDate());
            shoppingKillAbnormal.setRemark("秒杀");
            shoppingKillAbnormalRepository.save(shoppingKillAbnormal);
            return false;
        }
        // 1.修改订单支付状态（状态，支付时间，微信支付订单号）
        String s = order.getTradingStatus().toString();
        if(s.equals("unpaid")){
            order.setTradingStatus(ShoppingKillTradingRecord.TradingStatus.paid);
            order.setPayTime(DateUtils.currentDate());
            order.setTransactionId(transactionId);
            shoppingKillTradingRecordRepository.saveAndFlush(order);
            stringRedisTemplate.delete(USER_NUM + order.getShoppingKillId() + STRING + order.getUseId());

            return true;
        }

        //修改真实的库存 TODO
        return false;
    }

    /**
     * 根据秒杀商品id查询记录
     *
     * @param shoppingKillId
     * @return
     */
    public Integer findAllByShoppingKillId(String shoppingKillId) {
        List<ShoppingKillTradingRecord> shoppingKillTradingRecords = shoppingKillTradingRecordRepository.findByShoppingKillId(shoppingKillId);
        //将库存量缓存回去 TODO
        return shoppingKillTradingRecords.size();
    }


    public List<ShoppingKillTradingRecord> queryAllRecord(String userId, Integer page, Integer size){
        List<ShoppingKillTradingRecord> list;
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Pageable pageable =  PageRequest.of(page, size, sort);
        ShoppingKillTradingRecord shoppingKillTradingRecord1 = new ShoppingKillTradingRecord();
        shoppingKillTradingRecord1.setUseId(userId);
        shoppingKillTradingRecord1.setTradingStatus(ShoppingKillTradingRecord.TradingStatus.paid);
        Example<ShoppingKillTradingRecord> example = Example.of(shoppingKillTradingRecord1);
        Page<ShoppingKillTradingRecord> findAll = shoppingKillTradingRecordRepository.findAll(example, pageable);
        list = findAll.getContent();

        for(ShoppingKillTradingRecord shoppingKillTradingRecord:list){
            String shoppingKillId = shoppingKillTradingRecord.getShoppingKillId();
            //根据秒杀商品id查询秒杀信息和价格
            ShoppingKill shoppingKill = shoppingKillRepository.findById(shoppingKillId).get();
            shoppingKillTradingRecord.setShoppingKillName(shoppingKill.getShoppingKillName());
            shoppingKillTradingRecord.setCoverImg(shoppingKill.getCoverUrl());
        }

        return list;
    }

    /**
     * 查询用户秒杀次数
     * @param userId
     * @param shoppingKillId
     * @return
     */
    public Integer findAllRecordCount(String userId, String shoppingKillId) {
        Integer allCount = shoppingKillTradingRecordRepository.findAllCount(userId, shoppingKillId);
        return allCount;
    }

    public Integer findDailyRecordCount(String userId, String shoppingKillId) {
        //获取当天时间的起始时间
        Map<String, Date> map = new HashMap<>();

        Map<String, Date> stringDateMap = CalendarUtil.setDayRange(map);
        Date startTime = stringDateMap.get("startTime");
        String startDate = DateUtils.parseDate2Str("yyyy-MM-dd HH:mm:ss", startTime);
        Integer dailyCount = shoppingKillTradingRecordRepository.findDailyCount(userId,shoppingKillId,startDate);
        return dailyCount;
    }
}
